<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Util;
use plugin\admin\app\model\Option;
use plugin\admin\app\model\Order;
use plugin\admin\app\model\TaskLog;
use plugin\admin\app\model\User;
use support\exception\BusinessException;
use support\Redis;
use support\Request;
use support\Response;
use Throwable;
use Workerman\Worker;

class IndexController
{

    /**
     * 无需登录的方法
     * @var string[]
     */
    protected $noNeedLogin = ['index', 'getData'];

    /**
     * 不需要鉴权的方法
     * @var string[]
     */
    protected $noNeedAuth = ['dashboard'];

    /**
     * 后台主页
     * @param Request $request
     * @return Response
     * @throws BusinessException|Throwable
     */
    public function index(Request $request): Response
    {
        clearstatcache();
        if (!is_file(base_path('plugin/admin/config/database.php'))) {
            return raw_view('index/install');
        }
        $admin = admin();
        if (!$admin) {
            $name = 'system_config';
            $config = Option::where('name', $name)->value('value');
            $config = json_decode($config, true);
            $title = $config['logo']['title'] ?? 'webman admin';
            $logo = $config['logo']['image'] ?? '/app/admin/admin/images/logo.png';
            return raw_view('account/login',['logo'=>$logo,'title'=>$title]);
        }
        return raw_view('index/index');
    }

    public function getData(): Response
    {
        // 查询重复的数据（假设你想根据 title 字段查找重复的数据）
        $res = TaskLog::limit(100)->get();
        foreach ($res as $key => $value) {
            $whereArr = [
                'spu_id' => $value['spu_id'],
                'consume_status' => 1
            ];
            $num = TaskLog::where($whereArr)->count();
            $res[$key]['num'] = $num;
        }
        if($res) {
            return json(['code' => 0, 'msg' => 'ok', 'data' => $res]);
        } else {
            return json(['code' => 0, 'msg' => 'ok', 'data' => []]);
        }
    }

    /**
     * 仪表板
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function dashboard(Request $request): Response
    {
        $orderInfo = OrderController::getOrder(admin());
        // 1. 今日消费总量
        $today_consume_num = TaskLog::where([
            'company_id'     => admin('company_id'),
            'consume_status' => 1, // 1是消费了，0是未消费
        ])->whereDate('created_at', date('Y-m-d', time()))->count();
        // 2. 上传成功
        $today_success_num = TaskLog::where([
            'company_id' => admin('company_id'),
            'up_status'  => 1
        ])->whereDate('created_at', date('Y-m-d', time()))->count();
        // 3. 已存在
        $today_existence_num = TaskLog::where([
            'company_id'     => admin('company_id'),
        ])->whereDate('created_at', date('Y-m-d', time()))->where('msg', 'like', '商家skuId已存在%')->count();
        // 4. 上传失败
        $today_error_num = 0;
        // 5. 解析成功
        $today_ana_num = TaskLog::where([
            'company_id' => admin('company_id'),
            'ana_status' => 1
        ])->whereDate('created_at', date('Y-m-d', time()))->count();
        // 6. 未搜索到数据
        $today_not_find_num = TaskLog::where([
            'company_id'     => admin('company_id'),
        ])->whereDate('created_at', date('Y-m-d', time()))->where('msg', 'like', '未搜索到相关数据%')->count();
        // 7. 解析失败
        $today_ana_error_num = TaskLog::where([
            'company_id'  => admin('company_id'),
            'status_code' => 1012
        ])->whereDate('created_at', date('Y-m-d', time()))->count();
        // 8 判断是否过期
        $stop_at = strtotime(admin('stop_at'));
        if(time() >= $stop_at) {
            $stop_msg = '已过期';
        } else {
            $stop_msg = '正常';
        }
        $stop_at = date("Y-m-d", $stop_at);

        return raw_view('index/dashboard',[
            'surplus_num'         => admin('num') - $orderInfo['today'],
            'max'                 => admin('num'),
            'today_consume_num'   => $today_consume_num,
            'today_success_num'   => $today_success_num,
            'today_error_num'     => $today_error_num,
            'today_existence_num' => $today_existence_num,
            'today_not_find_num'  => $today_not_find_num,
            'today_ana_num'       => $today_ana_num,
            'toady_ana_error_num' => $today_ana_error_num,
            'stop_at'             => $stop_at."(".$stop_msg.")"
        ]);
    }

}
